package com.photo.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photo.system.common.BaseResponse;
import com.photo.system.common.DeleteRequest;
import com.photo.system.common.ErrorCode;
import com.photo.system.common.ResultUtils;
import com.photo.system.exception.BusinessException;
import com.photo.system.exception.ThrowUtils;
import com.photo.system.model.dto.favour.FavourCountRequest;
import com.photo.system.model.dto.favour.FavourQueryRequest;
import com.photo.system.model.dto.favour.FavourAddRequest;
import com.photo.system.model.entity.ThingFavour;
import com.photo.system.model.entity.Things;
import com.photo.system.model.entity.User;
import com.photo.system.model.vo.LoginUserVO;
import com.photo.system.model.vo.ThingFavourVO;
import com.photo.system.service.ThingFavourService;
import com.photo.system.service.ThingsService;
import com.photo.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 摄影作品收藏接口
 *
 * @author xuwenhui
 */
@RestController
@RequestMapping("/favour")
@Slf4j
@Api(tags = {"摄影作品收藏接口"})
public class FavourController {

    @Resource
    private UserService userService;

    @Resource
    private ThingFavourService thingFavourService;

    @Resource
    private ThingsService thingsService;

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // region 增删改查

    /**
     * 新增摄影作品收藏
     *
     * @param favorAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增摄影作品收藏")
    public BaseResponse<Things> addThumb(@RequestBody FavourAddRequest favorAddRequest, HttpServletRequest request) {
        if (favorAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long userId = userService.getLoginUser(request).getId();

        QueryWrapper<Things> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ThingFavour> queryThingFavour = new QueryWrapper<>();
        queryThingFavour.eq("thingId", favorAddRequest.getThingId());
        queryThingFavour.eq("userId", userId);
        if (thingFavourService.getOne(queryThingFavour) != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该作品已收藏");
        }
        ThingFavour favour = new ThingFavour();
        BeanUtils.copyProperties(favorAddRequest, favour);
        User loginUser = userService.getLoginUser(request);
        favour.setUserId(loginUser.getId());
        queryWrapper.eq("id", favour.getThingId());
        Things things = thingsService.getOne(queryWrapper);
        if (things == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "作品不存在");
        }

        boolean result = thingFavourService.save(favour);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "收藏失败");
        queryWrapper.eq("id", favour.getThingId());
        things = thingsService.getOne(queryWrapper);
        return ResultUtils.success(things);
    }

    /**
     * 删除作品收藏
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除作品收藏")
    public BaseResponse<Boolean> deleteThumb(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = getLoginUser(request).getData().getId();
        QueryWrapper<ThingFavour> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", deleteRequest.getId());
        ThingFavour favour = thingFavourService.getOne(queryWrapper);
        if (!userId.equals(favour.getUserId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限删除");
        }
        boolean result = thingFavourService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 获取用户全部收藏作品
     *
     * @param request
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "获取用户全部收藏作品")
    public BaseResponse<Page<ThingFavourVO>> getFavour(@RequestBody FavourQueryRequest favourQueryRequest, HttpServletRequest request) {
        Long userId = getLoginUser(request).getData().getId();

        long current = favourQueryRequest.getCurrent() == 0 ? 1 : favourQueryRequest.getCurrent();
        long size = favourQueryRequest.getPageSize() == 0 ? 10 : favourQueryRequest.getPageSize();

        Page<ThingFavourVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ThingFavourVO> pageThumbs = thingFavourService.getAllFavour(pageParam, favourQueryRequest, userId);

        return ResultUtils.success(pageThumbs);
    }

    /**
     * 获取摄影作品的收藏总数
     *
     * @param favorCountRequest
     * @return
     */
    @PostMapping("/get/all/count")
    @ApiOperation(value = "获取摄影作品的收藏总数(所有人)")
    public BaseResponse<Long> getFavour(@RequestBody FavourCountRequest favorCountRequest) {

        QueryWrapper<ThingFavour> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("thingId", favorCountRequest.getThingId());
        Long count = thingFavourService.count(queryWrapper);

        return ResultUtils.success(count);
    }


    // endregion

    /**
     * 用户作品的收藏摄影作品总数
     *
     * @param request
     * @return
     */
    @PostMapping("/get/all/number")
    @ApiOperation(value = "用户作品的收藏摄影作品总数")
    public BaseResponse<Long> getFavourCount(HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        Long id = loginUser.getId();
        QueryWrapper<ThingFavour> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", id);

        long count = thingFavourService.count(queryWrapper);
        if (count <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户没有收藏作品");
        }
        return ResultUtils.success(count);
    }
}
